package com.baizhi.action;

import com.baizhi.entity.Answer;
import com.baizhi.entity.Page;
import com.baizhi.entity.Survey;
import com.baizhi.service.PageService;
import com.baizhi.service.SurveyService;
import com.baizhi.service.impl.PageServiceImpl;
import com.baizhi.service.impl.SurveyServiceImpl;
import com.baizhi.util.StringUtil;
import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ParameterAware;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EngageSurveyAction  implements ParameterAware {
    private SurveyService ss=new SurveyServiceImpl();
    private PageService ps=new PageServiceImpl();
    private List<Survey> surveyList;
    private Survey survey;
    private Page curPage;
    private int curPid=1;
    //接受提交参数map
    private Map<String, String[]> paramsMap;
    public String findAllAvailableSurveys(){
        surveyList = ss.findAllAvailableSurveys();
        return "engageSurveyListPage";
    }
    public String entry(){
        //查询调查的首页-->currPage
        curPage = ps.selectPageByPageno(survey.getId(),1);
        survey=ss.selectOnlySurvey(survey.getId());
        //将survey --> session
        ActionContext.getContext().getSession().put("survey",survey);
        ActionContext.getContext().getSession().put("all_params", new HashMap<Integer, Map<String,String[]>>());
        return "engageSurveyPage" ;
    }
    public String doEngageSurvey(){
        String submitName = getSubmitName();
        //上一步
        if(submitName.endsWith("pre")){
			mergeParamsIntoSession();
            Survey survey = (Survey) ActionContext.getContext().getSession().get("survey");
            curPid--;
			this.curPage =  ps.selectPageByPageno(survey.getId(),curPid);
            return "engageSurveyPage" ;
        }
        //下一步
        else if(submitName.endsWith("next")){
			mergeParamsIntoSession();
            Survey survey = (Survey) ActionContext.getContext().getSession().get("survey");
            curPid++;
			this.curPage =  ps.selectPageByPageno(survey.getId(),curPid);
            return "engageSurveyPage" ;
        }
        //完成
        else if(submitName.endsWith("done")){
			mergeParamsIntoSession();
            //TODO 答案入库
            return "engageSurveyAction" ;
        }
        //退出
        else if(submitName.endsWith("exit")){
//			clearSessionData();
            ServletActionContext.getRequest().getSession().removeAttribute("survey");
            ServletActionContext.getRequest().getSession().removeAttribute("all_params");
            return "engageSurveyAction" ;
        }
        return null ;
    }

    /**
     * 处理答案
     */
    private List<Answer> processAnswers() {
        //矩阵式单选按钮
        Map<Integer, String> matrixRadioMap = new HashMap<Integer, String>();

        List<Answer> answers = new ArrayList<Answer>();
        Answer a = null ;
        String key = null ;
        String[] value = null ;
        Map<Integer,Map<String,String[]>> all_params = (Map<Integer,Map<String,String[]>>)ServletActionContext.getRequest().getSession().getAttribute("all_params");
        Survey survey=(Survey)ServletActionContext.getRequest().getSession().getAttribute("survey");

        for(Map<String,String[]> map : all_params.values()){
            for(Map.Entry<String, String[]> entry : map.entrySet()){
                key = entry.getKey();
                value = entry.getValue();
                //挑选所有q开头的参数
                if(key.startsWith("q")){
                    //不含other,也不含"_"
                    if(!key.contains("other") && !key.contains("_")){
                        a = new Answer();
                        a.setAnswerids(StringUtil.arr2Str(value));//answerids
                        a.setQuestionid(getQid(key));//questionid
                        a.setSurveyid(survey.getId());//surveyid
                        //处理其他项
                        String[] otherValue = map.get(key+"other");
                        a.setOtheranswer(StringUtil.arr2Str(otherValue));//otheranswer
                        answers.add(a);
                    }
                    //处理矩阵式单选按钮
                    else if(key.contains("_")){
                        //问题
                        Integer qid = getMatrixRadioQid(key);
                        String oldValue = matrixRadioMap.get(qid);
                        if(oldValue == null){
                            matrixRadioMap.put(qid, StringUtil.arr2Str(value));
                        }
                        else{
                            matrixRadioMap.put(qid, oldValue + "," + StringUtil.arr2Str(value));
                        }
                    }
                }
            }
        }
        //单独处理矩阵式单选按钮
        processMatrixRadioAnswers(answers,matrixRadioMap);
        return answers;
    }

    /**
     * 单独处理矩阵式单选按钮
     */
    private void processMatrixRadioAnswers(List<Answer> answers,
                                           Map<Integer, String> matrixRadioMap) {
        Integer key = null ;
        String value = null ;
        Answer a = null ;
        Survey survey=(Survey)ServletActionContext.getRequest().getSession().getAttribute("survey");

        for(Map.Entry<Integer, String> entry : matrixRadioMap.entrySet()){
            key = entry.getKey();
            value = entry.getValue();
            a = new Answer();
            a.setAnswerids(value);//answerids
            a.setQuestionid(key);
            a.setSurveyid(survey.getId());//surveyid
            answers.add(a);
        }
    }
    /**
     * 得到矩阵式单选按钮问题id:q12_0 --> 12
     */
    private Integer getMatrixRadioQid(String key) {
        return Integer.parseInt(key.substring(1, key.indexOf("_")));
    }
    //提取问题id:q12-->12
    private Integer getQid(String key) {
        return Integer.parseInt(key.substring(1));
    }
    public SurveyService getSs() {
        return ss;
    }

    public void setSs(SurveyService ss) {
        this.ss = ss;
    }

    public List<Survey> getSurveyList() {
        return surveyList;
    }

    public void setSurveyList(List<Survey> surveyList) {
        this.surveyList = surveyList;
    }

    public PageService getPs() {
        return ps;
    }

    public void setPs(PageService ps) {
        this.ps = ps;
    }

    public Survey getSurvey() {
        return survey;
    }

    public void setSurvey(Survey survey) {
        this.survey = survey;
    }

    public Page getCurPage() {
        return curPage;
    }

    public void setCurPage(Page curPage) {
        this.curPage = curPage;
    }
    @Override
    public void setParameters(Map<String, String[]> parameters) {
        this.paramsMap=parameters;
    }
    /**
     * 得打提交按钮的名称
     */
    private String getSubmitName() {
        for(String name : paramsMap.keySet()){
            if(name.startsWith("submit_")){
                return name ;
            }
        }
        return null;
    }

    /**
     * 将参数合并到session中
     */
    private void mergeParamsIntoSession() {
        Map<Integer, Map<String,String[]>> allParamsMap = (Map<Integer, Map<String,String[]>>)ServletActionContext.getRequest().getSession().getAttribute("all_params");
        allParamsMap.put(curPid, paramsMap);
    }

    public int getCurPid() {
        return curPid;
    }

    public void setCurPid(int curPid) {
        this.curPid = curPid;
    }
}
